package com.example.movie.ui.user.auth

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.*
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.example.movie.R
import com.example.movie.common.dsl.afterTextChanged
import com.example.movie.data.user.login.factory.LoginViewModelFactory
import com.example.movie.data.user.login.model.LoggedInUserView
import com.example.movie.data.user.login.model.SharedLoginViewModel
import com.example.movie.ui.MainActivity
import com.example.movie.utils.ContextHolder
import com.example.movie.utils.ToastUtil
import kotlinx.android.synthetic.main.fragment_login.*
import java.util.*


class LoginActivity : AppCompatActivity() {

    private val loginViewModel: SharedLoginViewModel by viewModels(factoryProducer = { LoginViewModelFactory() })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_login)
        initLoginForm()
        loadDataIfHasLoginBefore()
    }

    private fun initLoginForm() {
        back.setOnClickListener {
            onBackPressed()
        }
        to_register.setOnClickListener {
            startActivity(Intent(this, RegisterActivity::class.java))
        }

        show_password.setOnClickListener {
            showOrHidePassword()
        }

        username_clear_btn.setOnClickListener {
            clearEditText(it)
        }

        password_clear_btn.setOnClickListener {
            clearEditText(it)
        }

        login.setOnClickListener {
            loginViewModel.login(username.text.toString(), password.text.toString())
        }

        loginViewModel.loginFormState.observe(this, Observer {
            val loginState = it ?: return@Observer
            // disable login button unless both username / password is valid
            login.isEnabled = loginState.isDataValid

            if (loginState.usernameError != null) {
                username.error = getString(loginState.usernameError)
            }
            if (loginState.passwordError != null) {
                password.error = getString(loginState.passwordError)
            }
        })

        loginViewModel.loginResult.observe(this, Observer {
            val loginResult = it ?: return@Observer
            if (loginResult.error != null) {
                showLoginFailed(loginResult.error)
            }
            if (loginResult.success != null) {
                updateUiWithUser(loginResult.success)
                //登陆成功，更新登陆VM值，并存于mainActivity的VM中
                ContextHolder.from(MainActivity::class).loginViewModel.loginResult.value = loginViewModel.loginResult.value
                setResult(Activity.RESULT_OK)
                finish()
            }

        })

        username.apply {
            afterTextChanged {
                if (username.text.isEmpty()) {
                    username_clear_btn.visibility = View.GONE
                } else {
                    username_clear_btn.visibility = View.VISIBLE
                }
                loginViewModel.loginDataChanged(
                    username.text.toString(),
                    password.text.toString()
                )
            }

        }

        password.apply {
            afterTextChanged {
                if (password.text.isEmpty()) {
                    password_clear_btn.visibility = View.GONE
                } else {
                    password_clear_btn.visibility = View.VISIBLE
                }
                loginViewModel.loginDataChanged(
                    username.text.toString(),
                    password.text.toString()
                )
            }

            setOnEditorActionListener { _, actionId, _ ->
                when (actionId) {
                    EditorInfo.IME_ACTION_DONE ->
                        loginViewModel.login(
                            username.text.toString(),
                            password.text.toString()
                        )
                }
                false
            }
        }

    }


    /**
     * 加载用户已经登陆成功的用户名和密码
     */
    private fun loadDataIfHasLoginBefore() {
        val sharedPrefer =
            this.getSharedPreferences(
                getString(R.string.login_store_file_name),
                MODE_PRIVATE
            )
        username.setText(sharedPrefer.getString(getString(R.string.login_username), ""))
        password.setText(sharedPrefer.getString(getString(R.string.login_password), ""))
    }


    private fun updateUiWithUser(model: LoggedInUserView) {
        val welcome = getString(R.string.welcome)
        val displayName = model.nickName
        ToastUtil.makeTextLong(
            this,
            "$welcome $displayName",
        )
    }

    private fun showLoginFailed(@StringRes errorString: Int) {
        Toast.makeText(this, errorString, Toast.LENGTH_SHORT).show()
    }

    /**
     * 点击之后显示或者隐藏密码
     */
    private fun showOrHidePassword() {
        if (show_password.isChecked) {
            password.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
        } else {
            password.inputType =
                InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }
        // 设置光标到未能本末尾
        val charSequence: CharSequence = password.text
        if (charSequence is Spannable) {
            Selection.setSelection(charSequence, charSequence.length)
        }

    }


    /**
     * 清除编辑框信息
     */
    private fun clearEditText(view: View) {
        when (view.id) {
            R.id.username_clear_btn -> username.setText("")
            R.id.password_clear_btn -> password.setText("")
        }
    }

}





